//
//  AIUIHelperManager.m
//  MiaMind
//
//  Created by Vill on 2023/11/23.
//

#import "AIUIHelperManager.h"

@implementation AIUIHelperManager

+ (instancetype)shared{
    static dispatch_once_t once;
    static AIUIHelperManager *instance;
    dispatch_once(&once, ^{
        instance = [[AIUIHelperManager alloc] init];
    });
    return instance;
}

/// 当前控制器
+ (UIViewController *)currentViewController{
    UIViewController *result = nil;
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal) {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for (UIWindow *temp in windows) {
            if (temp.windowLevel == UIWindowLevelNormal) {
                window = temp;
                break;
            }
        }
    }
    //取当前展示的控制器
    result = window.rootViewController;
    while (result.presentedViewController) {
        result = result.presentedViewController;
    }
    //如果为UITabBarController：取选中控制器
    if ([result isKindOfClass:[UITabBarController class]]) {
        result = [(UITabBarController *)result selectedViewController];
    }
    //如果为UINavigationController：取可视控制器
    if ([result isKindOfClass:[UINavigationController class]]) {
        result = [(UINavigationController *)result visibleViewController];
    }
    return result;
}

/// 获取当前导航
+ (UINavigationController *)currentNavC{
    if (![[UIApplication sharedApplication].windows.lastObject isKindOfClass:[UIWindow class]]) {
        NSAssert(0, @"未获取到导航控制器");
        return nil;
    }
    UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    return [self getCurrentNCFrom:rootViewController];
}

/// 获取当前控制器
+ (UIViewController *)currentVC{
    UIViewController *result = nil;
    UIWindow * window = [self keyWindow];
    if (window.windowLevel != UIWindowLevelNormal){
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows){
            if (tmpWin.windowLevel == UIWindowLevelNormal){
                window = tmpWin;
                break;
            }
        }
    }
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;
    if ([result isKindOfClass:[UIViewController class]]) {
        result = [self topVC:result];
    }
    return result;
}

//+ (UIWindow *)keyWindow {
//    UIWindow *keyWindow = nil;
//    if (@available(iOS 15.0, *)) {
//        for (UIWindowScene *scene in [UIApplication sharedApplication].connectedScenes) {
//            if (scene.activationState == UISceneActivationStateForegroundActive) {
//                for (UIWindow *window in scene.windows) {
//                    if (window.isKeyWindow) {
//                        keyWindow = window;
//                        break;
//                    }
//                }
//            }
//            if (keyWindow) {
//                break;
//            }
//        }
//    } else if (@available(iOS 13.0, *)) {
//        UIWindowScene *scene = (UIWindowScene *)[UIApplication sharedApplication].connectedScenes.allObjects.firstObject;
//        keyWindow = scene.windows.firstObject;
//    } else {
//        keyWindow = [UIApplication sharedApplication].keyWindow;
//    }
//    return keyWindow;
//}

+ (UIWindow *)keyWindow {
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    return keyWindow;
}

+ (UINavigationController *)getCurrentNCFrom:(UIViewController *)vc{
    if ([vc isKindOfClass:[UITabBarController class]]) {
        UINavigationController *nc = ((UITabBarController *)vc).selectedViewController;
        return [self getCurrentNCFrom:nc];
    }else if ([vc isKindOfClass:[UINavigationController class]]) {
        if (((UINavigationController *)vc).presentedViewController) {
            return [self getCurrentNCFrom:((UINavigationController *)vc).presentedViewController];
        }
        return [self getCurrentNCFrom:((UINavigationController *)vc).topViewController];
    }else if ([vc isKindOfClass:[UIViewController class]]) {
        if (vc.presentedViewController) {
            return [self getCurrentNCFrom:vc.presentedViewController];
        }else {
            return vc.navigationController;
        }
    }else {
        NSAssert(0, @"未获取到导航控制器");
        return nil;
    }
}

+ (UIViewController*)topVC:(UIViewController*)vc{
    UIViewController *result = vc;
    if ([vc isKindOfClass:[UITabBarController class]]) {
        UITabBarController *tabVC = (UITabBarController*)vc;
        result = tabVC.selectedViewController;
        result = [self topVC:result];
    }
    if ([vc isKindOfClass:[UINavigationController class]]) {
        UINavigationController *navVC = (UINavigationController*)vc;
        result = navVC.topViewController;
        result = [self topVC:result];
    }
    return result;
}

//计算label文字高度
+(float)getLabelHeight:(NSString *)text defaultWidth:(float)Width font:(UIFont *)font{
    CGSize size = CGSizeMake(Width,CGFLOAT_MAX);
    CGSize labelsize;
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_7_0
    NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName,nil];
    labelsize = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size;
#else
    labelsize = [text sizeWithFont:font constrainedToSize:size lineBreakMode:NSLineBreakByWordWrapping];
#endif
    //这里最好加+1(有可能计算有误差,tag:服务详情商品描述文字)
    return labelsize.height+1;
}

//计算label文字宽度
+(float)getLabelWidth:(NSString *)text defaultHeight:(float)Height font:(UIFont *)font{
    CGSize size = CGSizeMake(CGFLOAT_MAX,Height);
    CGSize labelsize;
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_7_0
    NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:font ,NSFontAttributeName,nil];
    labelsize = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size;
#else
    labelsize = [text sizeWithFont:font constrainedToSize:size lineBreakMode:NSLineBreakByWordWrapping];
#endif
    return labelsize.width;
}

// 计算文本size
+ (CGSize)getlabelSize:(NSString *)text width:(float)maxWidth font:(UIFont *)font{
    if (![text strHasValue]){
        return CGSizeZero;
    }
    NSStringDrawingOptions options =  NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading | NSStringDrawingTruncatesLastVisibleLine;
    CGRect textRect = [text boundingRectWithSize:CGSizeMake(maxWidth, 8000) options:options attributes:@{NSFontAttributeName:font} context:nil];
    // 这里宽度高度要取整数 不然会出现一条黑色的线条
    // 导致这个问题的原因是非整数的宽高导致的，像素高的机型会出现。
    // “ceil是表示向上取整,即向正无穷靠拢,而floor是向下取整,即向负无穷靠拢。
    return  CGSizeMake(ceil(textRect.size.width), ceil(textRect.size.height));
}

+ (void)exs_showloading{
    [MBProgressTool mb_showHUDInView:[AIUIHelperManager keyWindow]];
}

+ (void)exs_hideLoading{
    [MBProgressTool mb_hideHUDInView:[AIUIHelperManager keyWindow]];
}

// 获取获取我的金币数量
- (void)getMyBalance{
    [AIManager requestMethod:@"GET" url:api_coinBalance parameters:@{} successBlock:^(id  _Nullable result) {
        NSLog(@"getMyCoin ------ %@",result);
        // 更新金币数量
        AIUserInfoModel *userInfo = [AIUserInfoManager shareManager].userInfo;
        userInfo.coinBalance = [result integerValue];
        userInfo.regstier = NO;
        [[AIUserInfoManager shareManager] updateUserInfo:userInfo];
        NTFPost(BalanceUpdateNotification, nil);
    } failedBlock:^(NSError * _Nullable error) {
        NSLog(@"%@",error);
    } showHUD:NO];
}

// 顶部话题
- (NSArray *)topicChatTop{
    return [MNCacheClass mn_getSaveModelArrayWithkey:@"TopicChatTopModel" modelClass:[AITopicChatTopModel class]];
}

- (void)setTopicChatTop:(NSArray *)topicChatTop{
    [MNCacheClass mn_saveModel:topicChatTop key:@"TopicChatTopModel"];
}

//获取聊天框顶部的话题
- (void)loadTopicChatTop{
    [AIManager requestMethod:@"GET" url:api_topicChatTop parameters:@{} successBlock:^(id  _Nullable result) {
        AIUIHelperManager.shared.topicChatTop = [AITopicChatTopModel mj_objectArrayWithKeyValuesArray:result];
    } failedBlock:^(NSError * _Nullable error) {
        NSLog(@"%@",error);
    } showHUD:NO];
}

@end
